import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lui/flutter_lui.dart';
import 'package:flutter_lui/src/l_style.dart';

/// 富文本
class LRichText extends StatelessWidget {
  /// 最大行数
  final int? maxLines;

  /// 富文本
  final List<LSpan> text;

  /// 外边距
  /// - [1]=>all
  /// - [1,1]=>[上下，右左]
  /// - [1,1,1]=> [上，右左，下]
  /// - [1,1,1,1]=> [上，右，下，左]
  final List<double> margin;

  /// 左外边距
  final double? marginLeft;

  /// 右外边距
  final double? marginRight;

  /// 上外边距
  final double? marginTop;

  /// 下外边距
  final double? marginBottom;

  /// 上下外边距
  final double? marginVertical;

  /// 左右外边距
  final double? marginHorizontal;
  const LRichText({
    required this.text,
    this.maxLines,
    this.margin = const [0],
    this.marginLeft,
    this.marginRight,
    this.marginTop,
    this.marginBottom,
    this.marginVertical,
    this.marginHorizontal,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget view = RichText(
      maxLines: maxLines,
      text: TextSpan(
        children: text
            .map((e) => TextSpan(
                text: e.text,
                style: TextStyle(
                    fontWeight: e.fontWidget,
                    backgroundColor: e.backgroundColor,
                    fontSize: e.fontSize ?? LStyle.fontSize,
                    color: e.color ?? LUI.instance.textColor,
                    decoration: e.textDecoration),
                recognizer: TapGestureRecognizer()..onTap = e.onTap))
            .toList(),
      ),
    );
    var marginValue = findTRBL(margin);
    var mt = marginTop ?? marginVertical ?? marginValue[0] ?? 0;
    var mr = marginRight ?? marginHorizontal ?? marginValue[1] ?? 0;
    var mb = marginBottom ?? marginVertical ?? marginValue[2] ?? 0;
    var ml = marginLeft ?? marginHorizontal ?? marginValue[3] ?? 0;
    if (mt != 0 || mr != 0 || mb != 0 || ml != 0) {
      view = Padding(
          padding: EdgeInsets.only(top: mt, right: mr, bottom: mb, left: ml),
          child: view);
    }
    return view;
  }
}

class LSpan {
  final String text;
  final double? fontSize;
  final Color? color;
  final Color? backgroundColor;
  final TextDecoration? textDecoration;
  final FontWeight? fontWidget;
  final void Function()? onTap;
  LSpan(
      {required this.text,
      this.fontSize,
      this.color,
      this.textDecoration,
      this.onTap,
      this.backgroundColor,
      this.fontWidget});
}
